#include "stdafx.h"
#include <sstream>

#include <ShlObj.h>
#include <Shlwapi.h>
#pragma comment( lib, "shlwapi.lib")
#include "../TinyXML/tinyxml.h"

#define EXIT_OPTION 4

#define FORCHECKOFF 0

/**************************************************************/
// GetInstance
//	- store the ONLY instance in global memory
//	- return the only instance by pointer
/*static*/ LoadGameState* LoadGameState::GetInstance(void)
{
	static LoadGameState s_Instance;

	return &s_Instance;
}


/**************************************************************/
// Enter
//	- reset the game & load resources
/*virtual*/ void LoadGameState::Enter(void)
{
	// Set background color
	SGD::GraphicsManager::GetInstance()->SetClearColor({ 5, 5, 5 });	// dark gray

	for (int i = 0; i < 52; i++)
	{
		if (i < 26)
			keyboard[i] = char(65 + i);
		else
			keyboard[i] = char(71 + i);
	}

	//m_hBackground =	SGD::GraphicsManager::GetInstance()->LoadTexture("resource/Graphics/Main_menu_background.jpg");
	m_hKeyboard = SGD::GraphicsManager::GetInstance()->LoadTexture("resource/Fonts/font1.png");
	m_cName[0] = '\0';
	m_nNameCursor = 0;
	wchar_t *path = nullptr;
	SHGetKnownFolderPath(FOLDERID_LocalAppData, NULL, NULL, &path);
	wstring newPath = path;
	newPath.append(L"\\MegaLands\\");
	char newStr[300];
	wcstombs_s(nullptr, newStr, newPath.c_str(), 300);

	

	//Set up char path
	string c_path = newStr;
	string c_path1 = c_path + "slot1.xml";
	string c_path2 = c_path + "slot2.xml";
	string c_path3 = c_path + "slot3.xml";

	//Set up wchar path
	wstring file1 = newPath + L"slot1.xml";
	wstring file2 = newPath + L"slot2.xml";
	wstring file3 = newPath + L"slot3.xml";

	//Create the files if they dont exist
	TiXmlDocument docTemp;

	TiXmlDocument doc1(c_path1.c_str());
	if (doc1.LoadFile())
	{
		TiXmlElement *xRoot = doc1.FirstChildElement();
		TiXmlElement *xPlayer = xRoot->FirstChildElement("Player");

		slot1 = name1 = xPlayer->Attribute("name");
		if (atoi(xPlayer->Attribute("level")) >= 5)
		{
			slot1.append("\tCOMPLETE");
			slot1Complete = true;
		}
		else
		{
			slot1.append("\tLevel ");
			slot1.append(xPlayer->Attribute("level"));
		}
	}
	else
	{
		docTemp.SaveFile(c_path1.c_str());
		slot1 = "Empty Slot";
	}

	TiXmlDocument doc2(c_path2.c_str());
	if (doc2.LoadFile())
	{
		TiXmlElement *xRoot = doc2.FirstChildElement();
		TiXmlElement *xPlayer = xRoot->FirstChildElement("Player");

		slot2 = name2 = xPlayer->Attribute("name");
		if (atoi(xPlayer->Attribute("level")) >= 5)
		{
			slot2Complete = true;
			slot2.append("\tCOMPLETE");
		}
		else
		{
			slot2.append("\tLevel ");
			slot2.append(xPlayer->Attribute("level"));
		}
	}
	else
	{
		docTemp.SaveFile(c_path2.c_str());
		slot2 = "Empty Slot";
	}

	TiXmlDocument doc3(c_path3.c_str());
	if (doc3.LoadFile())
	{
		TiXmlElement *xRoot = doc3.FirstChildElement();
		TiXmlElement *xPlayer = xRoot->FirstChildElement("Player");

		slot3 = name3 = xPlayer->Attribute("name");
		if (atoi(xPlayer->Attribute("level")) >= 5)
		{
			slot3Complete = true;
			slot3.append("\tCOMPLETE");
		}
		else
		{
			slot3.append("\tLevel ");
			slot3.append(xPlayer->Attribute("level"));
		}
	}
	else
	{
		docTemp.SaveFile(c_path3.c_str());
		slot3 = "Empty Slot";
	}
	choseSlot = false;
}
/**************************************************************/
// Exit
//	- deallocate / unload resources
/*virtual*/ void LoadGameState::Exit(void)
{
	//	SGD::GraphicsManager::GetInstance()->UnloadTexture(m_hBackground);
	SGD::GraphicsManager::GetInstance()->UnloadTexture(m_hKeyboard);
	int len = strlen(m_cName);
	for (int i = 0; i <= len; i++)
	{
		m_cName[i] = '\0';
	}
	m_nNameCount = 0;
	deleting = false;
}


/**************************************************************/
// Input
//	- handle user input
/*virtual*/ bool LoadGameState::Input(void)
{
	SGD::InputManager* pInput = SGD::InputManager::GetInstance();

	//CONTROLLER INPUT MAPPING
	//0 = A
	//1 = B
	//2 = X
	//3 = Y
	//4 = left Bumper
	// Press Escape to jump to the exit option

	if (m_bDialogOpen)
	{
		if (pInput->IsAnyKeyPressed())
		{
			if (pInput->IsKeyPressed(SGD::Key::Enter))
			{
				m_bDialogOpen = false;
				if (m_nNameCursor == strlen(keyboard) + 2)
					choseSlot = false;
			}
			else if (pInput->IsKeyPressed(SGD::Key::Backspace))
			{
				if (m_nNameCount > 0)
					m_cName[--m_nNameCount] = '\0';
				else
					m_nNameCursor = strlen(keyboard) + 2;
			}
			else if (pInput->IsKeyPressed(SGD::Key::Left))
			{
				--m_nNameCursor;
				if ((m_nNameCursor + 1) % 13 == 0)
					m_nNameCursor += 13;
				if (m_nNameCursor < int(strlen(keyboard) + 1))
					m_nNameCursor = strlen(keyboard) + 2;
			}
			else if (pInput->IsKeyPressed(SGD::Key::Right))
			{
				++m_nNameCursor;
				if (m_nNameCursor % 13 == 0)
					m_nNameCursor -= 13;
				if (m_nNameCursor > int(strlen(keyboard) + 2))
					m_nNameCursor = strlen(keyboard) + 1;
			}
			else if (pInput->IsKeyPressed(SGD::Key::Up))
			{
				m_nNameCursor -= 13;
				if (m_nNameCursor < 0)
					m_nNameCursor = strlen(keyboard) + 1;
			}
			else if (pInput->IsKeyPressed(SGD::Key::Down))
			{
				m_nNameCursor += 13;
				if (m_nNameCursor > int(strlen(keyboard) - 1) && m_nNameCursor < int(strlen(keyboard) + 13))
					m_nNameCursor = strlen(keyboard) + 1;
				else if (m_nNameCursor > int(strlen(keyboard) + 13))
					m_nNameCursor -= (m_nNameCursor / 13) * 13;
			}
			else if (m_nNameCount < 12 && ((pInput->GetAnyCharDown() >= 'A' && pInput->GetAnyCharDown() <= 'Z') || (pInput->GetAnyCharDown() >= 'a' && pInput->GetAnyCharDown() <= 'z')))
				m_cName[m_nNameCount++] = char(pInput->GetAnyCharDown());
		}
		else if (Game::GetInstance()->MenuConfirmInput())
		{
			if (m_nNameCursor == strlen(keyboard) + 1)
				m_bDialogOpen = false;
			else if (m_nNameCursor == strlen(keyboard) + 2)
			{
				choseSlot = false;
				m_bDialogOpen = false;
			}
			else
				m_cName[m_nNameCount++] = keyboard[m_nNameCursor];
		}
		else if (Game::GetInstance()->MenuBackInput())
		{
			if (m_nNameCount > 0)
				m_cName[--m_nNameCount] = '\0';
			else
				m_nNameCursor = strlen(keyboard) + 2;
		}
		else if (Game::GetInstance()->MenuRightInput())
		{
			++m_nNameCursor;
			if (m_nNameCursor % 13 == 0)
				m_nNameCursor -= 13;
			if (m_nNameCursor > int(strlen(keyboard) + 2))
				m_nNameCursor = strlen(keyboard) + 1;
		}
		else if (Game::GetInstance()->MenuLeftInput())
		{
			--m_nNameCursor;
			if ((m_nNameCursor + 1) % 13 == 0)
				m_nNameCursor += 13;
			if (m_nNameCursor < int(strlen(keyboard) + 1))
				m_nNameCursor = strlen(keyboard) + 2;
		}
		else if (Game::GetInstance()->MenuDownInput())
		{
			m_nNameCursor += 13;
			if (m_nNameCursor > int(strlen(keyboard) - 1) && m_nNameCursor < int(strlen(keyboard) + 13))
				m_nNameCursor = strlen(keyboard) + 1;
			else if (m_nNameCursor > int(strlen(keyboard) + 13))
				m_nNameCursor -= (m_nNameCursor / 13) * 13;
		}
		else if (Game::GetInstance()->MenuUpInput())
		{
			m_nNameCursor -= 13;
			if (m_nNameCursor < 0)
				m_nNameCursor = strlen(keyboard) + 1;
		}
	}
	else
	{
		//********************** alec's code*******************************\\
		
		if (Game::GetInstance()->MenuBackInput() && !deleting)
			m_nCursor = EXIT_OPTION; //Set the cursor to exit

		// Move cursor
		if (Game::GetInstance()->MenuDownInput())
		{
			++m_nCursor;

			// Wrap around
			if (m_nCursor > EXIT_OPTION)		// should enumerate the options
				m_nCursor = 0;
		}
		else if (Game::GetInstance()->MenuUpInput())
		{
			--m_nCursor;

			// Wrap around
			if (m_nCursor < 0)
				m_nCursor = EXIT_OPTION;
		}


		// Select an option?
		if (Game::GetInstance()->MenuConfirmInput())
		{
			wchar_t *path = nullptr;
			SHGetKnownFolderPath(FOLDERID_LocalAppData, NULL, NULL, &path);
			char newStr[200];
			wcstombs_s(nullptr, newStr, path, 200);
			loadPath = newStr;

			pAudio->PlayAudio(theGame->GetMenuConfirm());
			// Which option?
			if (m_nCursor == 0)		// SLOT 1
			{
				if (deleting && slot1 != "Empty Slot")
				{
					loadPath.append("\\MegaLands\\slot1.xml");
					remove(loadPath.c_str());
					deleting = false;
					slot1 = "Empty Slot";
				}
				else
				{
					if (slot1 == "Empty Slot")
					{
						m_bDialogOpen = true;
						choseSlot = true;
						m_nNameCursor = 0;
					}
					else
					{
						playerName = name1;
						loadPath.append("\\MegaLands\\slot1.xml");
						Game::GetInstance()->ChangeState(GameplayState::GetInstance());
					}
				}

				return true;
			}
			// Which option?
			else if (m_nCursor == 1)	//SLOT 2
			{
				if (deleting && slot2 != "Empty Slot")
				{
					loadPath.append("\\MegaLands\\slot2.xml");
					remove(loadPath.c_str());
					deleting = false;
					slot2 = "Empty Slot";
				}
				else
				{
					if (slot2 == "Empty Slot")
					{
						m_bDialogOpen = true;
						choseSlot = true;
						m_nNameCursor = 0;
					}
					else
					{
						playerName = name2;
						loadPath.append("\\MegaLands\\slot2.xml");
						Game::GetInstance()->ChangeState(GameplayState::GetInstance());
					}
				}

				return true;
			}
			else if (m_nCursor == 2)//SLOT 3
			{
				if (deleting && slot3 != "Empty Slot")
				{
					loadPath.append("\\MegaLands\\slot3.xml");
					remove(loadPath.c_str());
					deleting = false;
					slot3 = "Empty Slot";
				}
				else
				{
					if (slot3 == "Empty Slot")
					{
						m_bDialogOpen = true;
						choseSlot = true;
						m_nNameCursor = 0;
					}
					else
					{
						playerName = name3;
						loadPath.append("\\MegaLands\\slot3.xml");
						Game::GetInstance()->ChangeState(GameplayState::GetInstance());
					}
				}

				return true;
			}
			else if (m_nCursor == 3)//BACK
			{
				deleting = !deleting;
			}
			else if (m_nCursor == 4)//BACK
			{
				Game::GetInstance()->ChangeState(MainMenuState::GetInstance());
				return true;
			}
		}
	}
	return true;	// keep playing
}


/**************************************************************/
// Update
//	- update Objects / animations
/*virtual*/ void LoadGameState::Update(float elapsedTime)
{
	if (choseSlot && !m_bDialogOpen)
	{
		//file dialogue closed
		if (m_cName[0] == '\0')
		{
			strcpy_s(m_cName, "Magikus");
		}
		if (m_nCursor == 0)
		{
			playerName = m_cName;
			loadPath.append("\\MegaLands\\slot1.xml");
		}
		else if (m_nCursor == 1)
		{
			playerName = m_cName;
			loadPath.append("\\MegaLands\\slot2.xml");
		}
		else if (m_nCursor == 2)
		{
			playerName = m_cName;
			loadPath.append("\\MegaLands\\slot3.xml");
		}

		Game::GetInstance()->ChangeState(GameplayState::GetInstance());
	}
	else if (m_bDialogOpen)
	{
		if (m_nNameCount >= 12)
			m_nNameCursor = strlen(keyboard) + 1;
		else if (m_nNameCount < 0)
			m_nNameCount = 0;
	}
}


/**************************************************************/
// Render
//	- render Objects / menu options
/*virtual*/ void LoadGameState::Render(void)
{
	BitmapFont* pFont = Game::GetInstance()->GetFont();
	//	SGD::GraphicsManager::GetInstance()->DrawTexture(m_hBackground, { 0, 0 }, 0, {}, {}, { 1, 1 });
	SGD::GraphicsManager::GetInstance()->DrawTexture(theGame->GetMenuBackground(), { 0, 0 });
	if (m_bDialogOpen) // Name Dialog is open
	{
		pFont->Draw("Enter Your Name", 280, 20, 0.6f, {});
		pFont->Draw("Name: ", 50, 100, 0.6f, {});
		pFont->Draw(m_cName, 150, 100, 0.6f, {});

		std::ostringstream keyboardStream;

		int nlCount = 0;
		for (int i = 0; i < int(strlen(keyboard)); i++)
		{
			keyboardStream << keyboard[i];
			if ((i + 1) % 13 == 0)
			{
				keyboardStream << '\n';
				nlCount = 1;
			}
			else
				keyboardStream << ' ';
		}

		pFont->Draw(keyboardStream.str().c_str(), 50, 150, 0.6f, {});
		pFont->Draw("ACCEPT", 50, 300, 0.6f, {});
		pFont->Draw("CANCEL", 170, 300, 0.6f, {});

		if (m_nNameCursor < int(strlen(keyboard)))
		{
			SGD::Rectangle highlightRect;
			highlightRect.left = 50.0f + ((60 * .6f + 32 * .6f) * ((m_nNameCursor) % 13));
			highlightRect.top = 150.0f + ((64 * .6f) * ((m_nNameCursor) / 13));
			highlightRect.right = highlightRect.left + (60 * .6f);
			highlightRect.bottom = highlightRect.top + (64 * .6f);
			SGD::GraphicsManager::GetInstance()->DrawRectangle(highlightRect, { 120, 50, 50, 50 }, { 5, 5, 5 }, 2);
		}
		else if (m_nNameCursor == strlen(keyboard) + 1)
		{
			SGD::Rectangle highlightRect;
			highlightRect.left = 50.0f;
			highlightRect.top = 300.0f;
			highlightRect.right = highlightRect.left + (6 * (35 * .6f));
			highlightRect.bottom = highlightRect.top + (64 * .6f);
			SGD::GraphicsManager::GetInstance()->DrawRectangle(highlightRect, { 120, 50, 50, 50 }, { 5, 5, 5 }, 2);
		}
		else if (m_nNameCursor == strlen(keyboard) + 2)
		{
			SGD::Rectangle highlightRect;
			highlightRect.left = 170.0f;
			highlightRect.top = 300.0f;
			highlightRect.right = highlightRect.left + (6 * (35 * .6f));
			highlightRect.bottom = highlightRect.top + (64 * .6f);
			SGD::GraphicsManager::GetInstance()->DrawRectangle(highlightRect, { 120, 50, 50, 50 }, { 5, 5, 5 }, 2);
		}
	}
	else
	{
		//Alec's code*****

		// Use the game's font

		// Align text based on window width
		int width = (int)Game::GetInstance()->GetScreenWidth();
		// Display the game title centered at 2x scale
		pFont->Draw("Load", (int)((width - (4 * 32 * 4.0f)) / 2), 50, 2.0f, {});

		// Display the menu options centered at 1x scale
		pFont->Draw(slot1.c_str(), width / 5, 300, 0.7f, { 255, 0, 0 });
		pFont->Draw(slot2.c_str(), width / 5, 350, 0.7f, { 255, 0, 0 });
		pFont->Draw(slot3.c_str(), width / 5, 400, 0.7f, { 255, 0, 0 });
		if (!deleting)
			pFont->Draw("Delete", width / 5, 450, 0.7f, { 255, 0, 0 });
		else
			pFont->Draw("Load", width / 5, 450, 0.7f, { 255, 0, 0 });
		pFont->Draw("Back", width / 5, 500, 0.7f, { 255, 0, 0 });

		// Display the cursor next to the option
		SGD::GraphicsManager::GetInstance()->DrawTextureSection(theGame->GetCursorImage(), { 50, 300 + 50.0f * m_nCursor }, { 0, 0, 100, 35 });


	}






}
